import { defineStore } from 'pinia'
import { ref } from 'vue'

const initState: IAddress[] = []

export const useAddressStore = defineStore(
  'address',
  () => {
    const addressObj = uniCloud.importObject('address')

    const address = ref<IAddress[]>([...initState])
    onMounted(() => {
      // 获取地址列表
      addressObj.getList().then((res) => {
        console.dir(res)

        address.value = res.data
      })
    })

    /**
     * 获取默认地址
     */
    const defaultAddress = computed(() => {
      return address.value[0]
    })

    /**
     * 添加地址
     */
    const addAddress = async (data: Omit<IAddress, 'id'>) => {
      const obj = {
        id: new Date().getTime(),
        ...data,
      }
      const res = await addressObj.add(obj)
      if (res.id) {
        // 插入到第一个
        address.value.unshift(obj)
      }
      return res
    }

    /**
     * 删除地址
     */
    const delAddress = async (id: number) => {
      const res = await addressObj.delete(id)

      if (res.deleted === 1) {
        address.value = address.value.filter((item) => item.id !== id)
      }
      return res
    }

    /**
     * 选择地址
     */
    const selectAddress = (id: number) => {
      const index = address.value.findIndex((item) => item.id === id)
      if (index !== -1) {
        address.value.unshift(address.value.splice(index, 1)[0])
      }
    }

    return {
      address,
      defaultAddress,
      addAddress,
      delAddress,
      selectAddress,
    }
  },
  {
    persist: true,
  },
)
